package com.yazif.vqa.api.wechat.service.impl;

import com.yazif.vqa.api.wechat.domain.Authentication;
import com.yazif.vqa.api.wechat.domain.Message;
import com.yazif.vqa.api.wechat.service.WechatService;
import com.yazif.vqa.task.TargetChain;
import com.yazif.vqa.util.XmlUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;

@Service
@PropertySource("classpath:application.properties")
public class WechatServiceImpl implements WechatService{

    @Value("${spring.wechat.auth.token}")
    private String token;

    @Resource
    private TargetChain targetChain;


    @Override
    public String identifiyAuthentication(Authentication auth) {

        if (!checkAuthentication(auth)){
            return null;
        }

        String[] arr = {token, auth.getTimestamp(), auth.getNonce()};
        Arrays.sort(arr);

        StringBuilder content = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            content.append(arr[i]);
        }

        String buff = DigestUtils.sha1Hex(content.toString());
        buff = buff.toLowerCase();
        if (auth.getSignature().equals(buff)){
            return auth.getEchostr();
        }
        return null;
    }

    @Override
    public String callback(String messageXml) {
        Message recv = (Message) XmlUtils.toJavaBean(Message.class, messageXml);
        Message send = targetChain.execute(recv);
        return XmlUtils.toXML(send);
    }

    private boolean checkAuthentication(Authentication auth){
        if (auth == null){
            return false;
        } else if (StringUtils.isBlank(auth.getEchostr())){
            return false;
        } else if (StringUtils.isBlank(auth.getNonce())){
            return false;
        } else if (StringUtils.isBlank(auth.getSignature())){
            return false;
        } else if (StringUtils.isBlank(auth.getTimestamp())){
            return false;
        }
        return true;
    }
}
